/**
 * 判断是否是资源链接
*/
function isSourceUrl(target) {
    // console.log('target', target)
    if(target.includes('GetHttpImg')){
        return true;
    }
    return /(.png|.jpeg|.jpg|.gif|.svg|.mp3|.mp4)$/.test(target);
}

/**
 * 创建超链接
 * @param {String} url 链接
 * @param {String} text 显示文本
 */
function createHyperlink(url, text, className) {
    text = text || url;
    return `<a target='_blank' href="${url}" class="${className}">${text}</a>`;
}
/**
 * 随机字符串
 * @param {Object} len
 */
function randomString(len) {
    len = len || 32
    var chars = 'abcdefhijkmnprstwxyz'    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = chars.length
    var pwd = ''
    for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return pwd
}


/**
 * 保护A标签
 */
function protectATag(htmlText) {
    var aTagReg = /<a.*?>(.*?)<\/a>/ig;
    var aTagPlaceholdeMap = {};
    var newHtmlText = htmlText.replace(aTagReg, function (solt, index) {
        var key = randomString(10);
        aTagPlaceholdeMap[key] = solt;
        return "[[[placeholder-" + key + "]]]";
    });
    return {
        htmlText: newHtmlText,
        aTagPlaceholdeMap: aTagPlaceholdeMap
    }
}


/**
 * 还原A标签
 */
function restoreATag(htmlText, aTagPlaceholdeMap) {

    var placeholderReg = /\[\[\[placeholder-\S*\]\]\]/ig;
    var newHtmlText = htmlText.replace(placeholderReg, function (solt, index) {
        //提出去key
        var keyReg = /placeholder-(\S*)\]\]\]/;
        var execRES = keyReg.exec(solt);

        return aTagPlaceholdeMap[execRES[1]] || "";
    });
    return newHtmlText;
}

/**
 * 将html文本的网址地址转化为超链接
 * @param {String} htmlText html文本
 */
function extractUrlToLinks(htmlText, className = 'href-a') {
    if (!htmlText) {
        console.warn("传入的字符串不存在");
        return;
    }
    var urlReg = /http[s]*:\/\/[A-z0-9\.\?#-\/=]+/g;
    var newHtmlText = htmlText.replace(urlReg, function (slot, index) {
        // console.log('slot', slot)
        return isSourceUrl(slot) ? slot : createHyperlink(slot,slot,className);
    })
    return newHtmlText;
}

function returnRotesToLink(text, protectRes, extractUrlToLinksResult){
    // console.log('text', text)
    text = text.replace(/&amp;/g, '&')
    protectRes =  protectATag(text)
    extractUrlToLinksResult = extractUrlToLinks(protectRes.htmlText)
    return restoreATag(extractUrlToLinksResult, protectRes.aTagPlaceholdeMap)
}

function replaceLabel(str){
    if(str) return str.replace(/<[^>]+>/g, "") // 去掉所有的html标记
    return str
}

// 返回字符串是否包含数组中的某一元素
function strIsIncludeArrEle(str, arr){
    let end = false
    arr.forEach((val) => {
        if(str.includes(val)) end = true
    })
    return end
}

// 复制 ** 到剪切板
function copyStr(str){
    var save = function (e) {
        e.clipboardData.setData('text/plain', str);
        e.preventDefault();//阻止默认行为
    }
    document.addEventListener('copy', save);
    document.execCommand("copy");//使文档处于可编辑状态，否则无效
}

// 遍历对象属性拼接成Url参数格式的字符串
function objToUrlStr(obj, getType = 'get'){
    let str = '';
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            if(str){
                str += `&${key}=${obj[key]}`
            }else{
                if(getType === 'get'){
                    str = `?${key}=${obj[key]}`
                }else{
                    str = `${key}=${obj[key]}`
                }
            }
        }
    }
    return str
}

// 去掉所有的html标记
function delHtmlTag(str){
    if(str) return str.replace(/<[^>]+>/g, "")  //正则去掉所有的html标记
    return '';
}

//处理邮箱内容中间文字变为 ****
// 规则：取字符串前三位 + **** @ + @后面的内容
function setEmailStrToCharacterAll(emailStr) {
    if(emailStr) return emailStr.substr(0, 3) + "****" + `@${emailStr.split('@')[1]}`
    console.log('公用方法： setEmailStrToAllStr，传入参数：emailStr为空或其他无效值， emailStr：', emailStr)
    return '';
}

// 处理用户名称，多于x个则后面显示...，默认4个
function userNameManagementChange({name = '', count = 4}){
    if(name.length > count && typeof name === 'string'){
        return `${name.substring(0, count)}...`
    }
    return name || ''
}

//替换邮箱字符
function regEmail(email) {
    if (String(email).indexOf('@') > 0) {
        let str = email.split('@'),
            _s = '';
        if (str[0].length > 3) {
            for (let i = 0; i < str[0].length - 3; i++) {
                _s += '*';
            }
        }
        var new_email = str[0].substr(0, 3) + _s + '@' + str[1];
    }
    return new_email;
}

//用word方式计算正文字数
function getWordsSum(str) {
    let sLen = 0;
    try {
        //先将回车换行符做特殊处理
        str = str.replace(/(\r\n+|\s+|　+)/g, "龘");
        //去掉回车换行符
        str = str.replace(/龘+/g, "");
        //处理英文字符数字，连续字母、数字、英文符号视为一个单词
        str = str.replace(/[\x00-\xff]/g, "m");
        //合并字符m，连续字母、数字、英文符号视为一个单词
        str = str.replace(/m+/g, "*");

        //返回字数
        sLen = str.length;
    } catch (e) {

    }
    return sLen;
}

//手机号码中间四位变为****
function setPhoneNumberToXin(str) {
    return str.substr(0, 3) + "****" + str.substr(7)
}

// 生成哈希值
export function createHash (hashLength = 10) {
	if (!hashLength || typeof(Number(hashLength)) != 'number') {return;}
	let ar = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
	let hs = []
    ar.forEach(() => {
        hs.push(ar[Math.floor(Math.random() * ar.length)])
    })
	return hs.join('')
}

// 处理html()方法返回特殊符号的转义问题
export function escapeHtml(str) {
    let temp = "";
    if(str.length == 0) return ""
    temp = str.replace(/&amp;/g,"&")
    temp = temp.replace(/&lt;/g,"<")
    temp = temp.replace(/&gt;/g,">")
    temp = temp.replace(/&nbsp;/g," ")
    temp = temp.replace(/&#39;/g,"\'")
    temp = temp.replace(/&quot;/g,"\"")
    return temp
}

// 获取纯文本
export function getText(val) {
    if (val && typeof val === 'string') {
        return escapeHtml(delHtmlTag(val)).trim()
    }
    return ''
}

// 从str中获取图片标签的链接
export function getImgSrc (htmlStr) { 
    const reg = /<img.+?src=('|")?([^'"]+)('|")?(?:\s+|>)/gim
    const arr = []
    let tem;
    while (tem = reg.exec(htmlStr)) { 
        arr.push(tem[2])
    }
    // console.log('htmlStr', htmlStr)
    // console.log('arr', arr)
    return arr
}

// `asdasdasdsadasdasdas<p contenteditable="false" style=""><img class="up-img" src="https://www.mroyewubiji.com/Api/GetHttpImg/4d62a38c7f764b71a536c14f498135f5" loading="lazy" style=""></p><div class="stage-div" style="">kl.kl.kl</div><p contenteditable="false" style=""><img class="up-img" src="https://www.mroyewubiji.com/Api/GetHttpImg/8044b2806b4644eca0619b6fc112e04b" loading="lazy" style=""></p><div class="stage-div" style=""><img class="up-img" src="https://www.mroyewubiji.com/Api/GetHttpImg/4d62a38c7f764b71a536c14f498135f5" loading="lazy" style="">sdfsdfsdf</div>`

// 删除html的style
export const delHtmlStyle = (str) => {
    if (str) {
        var newHtml = ''
        if (str) {
            newHtml = str.replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/g, '')
        }
        return newHtml
    }
    return ''
}

export { restoreATag , extractUrlToLinks , protectATag , returnRotesToLink, replaceLabel, strIsIncludeArrEle, copyStr, objToUrlStr, delHtmlTag, setEmailStrToCharacterAll,
    userNameManagementChange, regEmail, getWordsSum, setPhoneNumberToXin
}